const App = {
    mixins: [Query],//配置文件，路径/utils/mixins.js
    data() {
        return {
            page: {
                activeName: 'first',
                value1: '',
                value2: '',
                PageNumber: 1, //页码
                RowAmount: 10,
                Condition: window.btoa(unescape(encodeURIComponent("%%,%%")))
            },
            form: {},
            form1: {},
            str1: '',
            personal_points_account: [],//积分账户
            showDialog1:false,
            AttachmentData:[],//查看附件
            fileUrl:'',
            showDialog2:false
        }
    },
    mounted() {

    },
    methods: {
        handleClick() {
            if (this.page.activeName == 'first') {
                this.str1 = '';
            } else if (this.page.activeName == 'second') {
                this.str1 = "\r\nAND personal_points_application.Row_Status = '2'";
            } else if (this.page.activeName == 'third') {
                this.str1 = "\r\nAND personal_points_application.Row_Status = '0'";
            } else if (this.page.activeName == 'fourth') {
                this.str1 = "\r\nAND personal_points_application.Row_Status = '3'";
            }
            this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent(this.str1)));
            this.postgetList(this.page)
        },
        check() {
            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.page.value1 + "%,%" + this.page.value2 + "%")));
            this.postgetList(this.page)
        },
        //树的点击筛选事件
        handleNodeClick(data, node) {
            this.page.value2 = data.Personal_Points_Application_Type_SerialNumber;
            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.page.value1 + "%,%" + this.page.value2 + "%")));
            this.postgetList(this.page)
        },
        handleAddPoints(row) {
            this.personal_points_account = [];
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'personal_points_account',
                    Condition: "ID_Card_Number='" + row.ID_SerialNumber + "' AND Points_Type='" + row.Points_Type + "'"
                },
                success: (data) => {
                    console.log(data);
                    this.personal_points_account = data;
                    this.form1 = {
                        Points_Type: row.Points_Type,
                        Points: 1,
                        Remain_Points: data.length > 0 ? data[0].Remain_Points : 0,
                        Children: {
                            personal_points_change_log_attachment: []
                        }
                    }
                    this.form = row;
                    this.showDialog = true;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });

        },
        async validateAllForms() {
            //获取当前页面上所有的Elform
            let forms = [];
            for (let key in this.$refs) {
                const ref = this.$refs[key];
                if (ref.$options && ref.$options.name == 'ElForm') {
                    forms.push(ref);
                }
            }
            //判断每个Elform的校验是否通过
            let isfail = false;
            for (const form of forms) {
                try {
                    await form.validate();
                } catch (error) {
                    isfail = true;
                }
            }
            if (isfail) {
                return false;
            }
            return true;
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                    method: "post",
                    data: {
                        Data: JSON.stringify([{
                            tableName: 'personal_points_application',
                            Condition: window.btoa(unescape(encodeURIComponent(`Personal_Points_Application_SerialNumber = '${this.form.Personal_Points_Application_SerialNumber}'`))),
                        }, {
                            tableName: 'personal_points_account',
                            Condition: window.btoa(unescape(encodeURIComponent("ID_Card_Number='" + this.form.ID_SerialNumber + "' AND Points_Type='" + this.form.Points_Type + "'"))),
                        }])
                    },
                    success: ({ personal_points_application, personal_points_account }) => {
                        let lJSONObject_DataSet = new Object();
                        personal_points_application[0].Row_Status = '0';
                        personal_points_application[0].Points = this.form1.Points;
                        if (personal_points_account.length == 1) {
                            personal_points_account[0].Remain_Points = accAdd(this.form1.Points, personal_points_account[0].Remain_Points);
                            personal_points_account[0].Total_Points = accAdd(this.form1.Points, personal_points_account[0].Total_Points);
                            lJSONObject_DataSet = {
                                Modify: {
                                    personal_points_account,
                                    personal_points_application
                                },
                                Add: {
                                    personal_points_change_log: [{
                                        ID_Card_Number: this.form.ID_SerialNumber,
                                        Points_Title: '积分申请通过增加' + (this.form1.Points_Type == '0' ? '村民积分' : '党员积分') + '积分',
                                        Points_Type: this.form.Points_Type,
                                        Change_Points: this.form1.Points,
                                        Remain_Points: personal_points_account[0].Remain_Points,
                                        Object_SerialNumber: this.form.Personal_Points_Application_SerialNumber,
                                        Notes: this.form1.Notes,
                                        Children: this.form1.Children
                                    }]
                                }
                            }
                        } else if (personal_points_account.length == 0) {
                            lJSONObject_DataSet = {
                                Add: {
                                    personal_points_change_log: [{
                                        ID_Card_Number: this.form.ID_SerialNumber,
                                        Points_Title: '积分申请通过增加' + (this.form1.Points_Type == '0' ? '村民积分' : '党员积分') + '积分',
                                        Points_Type: this.form.Points_Type,
                                        Change_Points: this.form1.Points,
                                        Remain_Points: this.form1.Points,
                                        Notes: this.form1.Notes,
                                        Children: this.form1.Children
                                    }],
                                    personal_points_account: [{
                                        ID_Card_Number: this.form.ID_SerialNumber,
                                        Points_Type: this.form.Points_Type,
                                        Total_Points: this.form1.Points,
                                        Remain_Points: this.form1.Points,
                                    }]
                                },
                                Modify: {
                                    personal_points_application
                                }
                            }
                        }
                        submitSave(lJSONObject_DataSet, (res) => {
                            if (res.Status == 'success') {
                                this.postgetList(this.page);
                                this.form1 = {};
                                this.form = {};
                                this.showDialog = false;
                                this.loading = false;
                            }
                        })
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                });
            }
        },
        handleRefuse(data) {
            this.$prompt("请输入拒绝原因", '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                inputPattern: /^\s*\S.+$/,
                inputErrorMessage: "请输入拒绝原因"
            }).then(({ value }) => {
                let { TableName, primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: TableName,
                        Condition: primary_key + "='" + data[primary_key] + "'"
                    },
                    success: (res) => {
                        if (res.length == 1) {
                            res[0].Row_Status = '3';
                            res[0].Reject_Reason = value;
                            let lJSONObject_DataSet = new Object();
                            let lJSONObject_Table = new Object();
                            lJSONObject_Table[TableName] = res;
                            lJSONObject_DataSet['Modify'] = lJSONObject_Table;
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            lJSONObject_DataSet['Add'] = new Object();
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSaveByRequestBody",
                                Operation_IP: getIpAddress()
                            }]
                            submitSave(lJSONObject_DataSet, (res) => {
                                if (res.Status == 'success') {
                                    this.postgetList(this.page);
                                    this.$message({
                                        type: 'success',
                                        message: '拒绝成功'
                                    });
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: '操作失败'
                                    });
                                }
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: '操作失败'
                            });
                        }
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest)
                    },
                });
            }).catch(() => { });
        },
        preview(row) {
            this.fileUrl = photo + row.Attachment_URL;
            this.showDialog2 = true;
        },
        async download(row) {
            // if (row.Attachment_URL) {
            //     window.location.href = photo + row.Attachment_URL;
            // }
            let apiUrl = photo + row.Attachment_URL;
            let fileName = apiUrl.split('/').pop();
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        handleAttachment(row){
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'personal_points_application_attachment',
                    Condition: "Personal_Points_Application_SerialNumber='" + row.Personal_Points_Application_SerialNumber + "'"
                },
                success: (data) => {
                   this.AttachmentData = data;
                   this.showDialog1 = true;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        }
    },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.component('yl-upload', ylUpload);
app.component('yl-online-preview', ylOnlinePreview);
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
